﻿using System;
using System.Collections.Generic;
using System.Data;

namespace DbMetadata.Providers
{
    /// <summary>
    /// Provides a base class for implementing provider specific 
    /// </summary>
    public abstract class DbMetadataExtractor :  IDbMetadataExtractor
    {
                
        /// <summary>
        /// Initializes a new instance of the <see cref="IDbMetadataExtractor"/> class.
        /// </summary>
        /// <param name="dbConnection"></param>
        protected DbMetadataExtractor(IDbConnection dbConnection)
        {
            DbConnection = dbConnection;
        }

        /// <summary>
        /// Returns a list of <see cref="TableInfo"/> instances.
        /// </summary>
        /// <returns>A <see cref="IEnumerable{T}"/> that contains <see cref="TableInfo"/> instances.</returns>
        public abstract IEnumerable<TableInfo> ReadTables();

        /// <summary>
        /// Returns a list of <see cref="ColumnInfo"/> instances.
        /// </summary>
        /// <returns>A <see cref="IEnumerable{T}"/> that contains <see cref="ColumnInfo"/> instances.</returns>
        public abstract IEnumerable<ColumnInfo> ReadColumns();

        /// <summary>
        /// Returns a list of <see cref="ForeignKeyInfo"/> instances.
        /// </summary>
        /// <returns>A <see cref="IEnumerable{T}"/> that contains <see cref="ForeignKeyInfo"/> instances.</returns>
        public abstract IEnumerable<ForeignKeyInfo> ReadForeignKeys();

        /// <summary>
        /// Returns a list of <see cref="PrimaryKeyInfo"/> instances.
        /// </summary>
        /// <returns>A <see cref="IEnumerable{T}"/> that contains <see cref="PrimaryKeyInfo"/> instances.</returns>
        public abstract IEnumerable<PrimaryKeyInfo> ReadPrimaryKeys();


        /// <summary>
        /// Gets or sets the <see cref="IDbConnection"/> instance that is used to retrieve database metadata.
        /// </summary>
        public IDbConnection DbConnection { get; set; }
        

        /// <summary>
        /// Provides database access to execute queries for meta data extraction.
        /// </summary>
        /// <param name="sql">The query to execute.</param>
        /// <returns>AN <see cref="IDataReader"/> that represents the result of the query.</returns>
        protected virtual IDataReader ExecuteReader(string sql)
        {
            if (DbConnection == null)
                throw new InvalidOperationException("The DbConnection property must be set before calling ExecuteReader");
            var command = DbConnection.CreateCommand();
            command.CommandText = sql;
            return command.ExecuteReader();
        }
    }
}
